<template>
  <el-card class="box-card">
    <!-- 卡片顶部添加品牌按钮 -->
    <el-button
      v-has="`btn.Trademark.add`"
      type="primary"
      icon="Plus"
      size="default"
      @click="addTrademark"
    >
      添加品牌
    </el-button>
    <el-table style="margin: 10px 0px" border :data="trademarkArr">
      <el-table-column
        label="序号"
        type="index"
        width="80px"
        align="center"
      ></el-table-column>
      <el-table-column label="品牌名称" prop="tmName" align="center">
      </el-table-column>
      <el-table-column label="品牌logo" align="center">
        <template #default="{ row, $index }">
          <img :src="row.logoUrl" style="height: 100px" />
        </template>
      </el-table-column>
      <el-table-column label="品牌操作" align="center">
        <template #default="{ row, $index }">
          <el-button
            v-has="`btn.Trademark.update`"
            type="primary"
            size="small"
            icon="Edit"
            @click="updateTrademark(row)"
          ></el-button>

          <el-popconfirm
            :title="`确定要删除${row.tmName}吗？`"
            width="250px"
            icon="Delete"
            @confirm="removeTradeMark(row.id)"
          >
            <template #reference>
              <el-button
                v-has="`btn.Trademark.remove`"
                type="danger"
                size="small"
                icon="Delete"
              ></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="limit"
      :page-sizes="[5, 10, 20, 50]"
      :background="true"
      layout="prev, pager, next, jumper,->, sizes, total"
      :total="total"
      @current-change="getHasTrademark"
      @size-change="sizeChange"
    />
  </el-card>
  <!-- 对话框组件：在添加和修改品牌的业务使用的结构 -->
  <el-dialog v-model="dialogFormVisible" :title="trademarkParams.id ? '修改品牌' : '添加品牌'">
    <el-form
      ref="ruleFormRef"
      style="width: 80%"
      :model="trademarkParams"
      :rules="rules"
    >
      <el-form-item label="品牌名称" label-width="100px" prop="tmName">
        <el-input v-model="trademarkParams.tmName" placeholder="请输入品牌名称"></el-input>
      </el-form-item>
      <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          action="/api/admin/product/fileUpload"
          :http-request="customUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <!-- 具名插槽：footer -->
    <template #footer>
      <el-button size="default" @click="cancel">
        取消
      </el-button>
      <el-button type="primary" size="default" @click="confirm(ruleFormRef)">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import {
  reqHasTradeMark,
  reqAddOrUpdateTrademark,
  reqDeleteTradeMark
} from '@/api/product/trademark'
import type { Records, TradeMarkResponseData, TradeMark } from '@/api/product/trademark/type'
import { ElMessage } from 'element-plus'
import type { UploadProps, FormRules, FormInstance } from 'element-plus'

// import useUserStore from '@/store/modules/user'

// //获取用户相关的仓库
// let userStore = useUserStore()

const pageNo = ref<number>(1) //当前页码
const limit = ref<number>(10) //每页展示多少条数据
const total = ref<number>(0) //存储已有品牌数据总数
const trademarkArr = ref<Records>([]) //存储已有品牌数据列表

const dialogFormVisible = ref<boolean>(false)

const ruleFormRef = ref<FormInstance>()

//定义收集新增品牌得数据
const trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: ''
})


const customUpload = (options:any) => {
  const formData = new FormData()
  formData.append('file', options.file)

  // 创建 XMLHttpRequest 对象
  const xhr = new XMLHttpRequest()
  xhr.open(options.method, options.action, true)

  // 设置请求头
  xhr.setRequestHeader('TOKEN', localStorage.getItem('TOKEN') || '') // 示例：设置认证令牌

  xhr.onload = function() {
    if (xhr.status === 200) {
      options.onSuccess(JSON.parse(xhr.responseText)) // 调用 onSuccess 处理函数
    } else {
      options.onError() // 调用 onError 处理函数
    }
  }
  xhr.send(formData)
}

//封装请求的函数
const getHasTrademark = async (pager = 1) => {
  //当前页码
  pageNo.value = pager
  const result: TradeMarkResponseData = await reqHasTradeMark(pageNo.value, limit.value)
  if (result.code == 200) {
    total.value = result.data.total
    trademarkArr.value = result.data.records
  }
}

onMounted(() => {
  getHasTrademark()
})

// const changePageNo = () => {
//   getHasTrademark()
// }

const sizeChange = () => {
  getHasTrademark()
}

// 添加品牌按钮的回调
const addTrademark = () => {
  dialogFormVisible.value = true
  //清空表单数据
  trademarkParams.tmName = ''
  trademarkParams.logoUrl = ''
  trademarkParams.id = undefined
  // //清理校验结果:方法一
  // ruleFormRef.value?.clearValidate('tmName')
  // ruleFormRef.value?.clearValidate('logoUrl')

  //清理校验结果:方法二
  nextTick(() => {
    ruleFormRef.value?.clearValidate('tmName')
    ruleFormRef.value?.clearValidate('logoUrl')
  })
}

// 修改品牌按钮的回调
const updateTrademark = (row: TradeMark) => {
  //清理校验结果
  nextTick(() => {
    ruleFormRef.value?.clearValidate('tmName')
    ruleFormRef.value?.clearValidate('logoUrl')
  })

  dialogFormVisible.value = true

  // trademarkParams.id = row.id
  // trademarkParams.tmName = row.tmName
  // trademarkParams.logoUrl = row.logoUrl

  //ES6语法合并对象
  Object.assign(trademarkParams, row)
}

//对话框底部取消按钮
const cancel = () => {
  dialogFormVisible.value = false
}

//对话框底部确定按钮
const confirm = async (formEl: FormInstance | undefined) => {
  //在发请求前，要对整个表单进行校验
  //调用这个方法进行全部表单项的校验，如果校验全部通过再执行后面的语句
  await formEl?.validate()

  const result: any = await reqAddOrUpdateTrademark(trademarkParams)
  if (result.code == 200) {
    //关闭对话框
    dialogFormVisible.value = false
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? '修改品牌成功！' : '添加品牌成功！'
    })
    //再次发请求获取已有全部的品牌
    getHasTrademark(trademarkParams.id ? pageNo.value : 1)
  } else {
    ElMessage({
      type: 'error',
      message: trademarkParams.id ? '修改品牌失败！' : '添加品牌失败！'
    })
    //关闭对话框
    dialogFormVisible.value = false
  }
}

//上传图片之前触发的钩子函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type == 'image/png' || rawFile.type == 'image/jpeg' || rawFile.type == 'image/gif') {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传的文件必须小于4M'
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传的文件格式必须是PNG|JPG|GIF'
    })
    return false
  }
}

//图片上传成功的钩子函数
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  //收集上传的图片的地址，将来添加一个新的品牌的时候带给服务器
  trademarkParams.logoUrl = response.data
  //图片上传成功，清理对应图片校验结果
  ruleFormRef.value?.clearValidate('logoUrl')
}

const validateTmName = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('品牌名称位数必须大于等于两位'))
  }
}

const validateLogoUrl = (rule: any, value: any, callback: any) => {
  //自定义校验规则,如果图片上传了就放行
  if (value) {
    callback()
  } else {
    callback(new Error('LOGO图片务必上传！'))
  }
}

const rules = reactive<FormRules<typeof trademarkParams>>({
  tmName: [{ validator: validateTmName, required: true, trigger: 'blur' }],
  logoUrl: [{ validator: validateLogoUrl, required: true, trigger: 'blur' }]
})

//气泡确认框确定按钮的回调
const removeTradeMark = async (id: number) => {
  const result = await reqDeleteTradeMark(id)
  if (result.code == 200) {
    //重新发请求
    getHasTrademark(trademarkArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
    ElMessage({
      type: 'success',
      message: '删除品牌成功！'
    })
  } else {
    ElMessage({
      type: 'error',
      message: '删除品牌失败！'
    })
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
